package com.az.order.util;

import java.util.*;
import java.util.stream.Collectors;

import com.az.miaoapi.exception.BaseException;
import com.az.miaoapi.response.ResponseCode;
import com.az.order.domain.po.OrderDetail;
import com.az.order.domain.po.Orders;
import com.az.order.service.OrderDetailService;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Component
public class OrderUtils {

    @Resource
    private OrderDetailService orderDetailService;



    public List<Integer> collectProductIds(List<Orders> orderList) {
        Set<Integer> productIdsSet = new HashSet<>();
        for (Orders order : orderList) {
            Long orderId = order.getOrderId();
            List<OrderDetail> orderDetails = getOrderDetails(orderId);
            for (OrderDetail orderDetail : orderDetails) {
                productIdsSet.add(orderDetail.getProductId());
            }
        }
        return new ArrayList<>(productIdsSet);
    }

    public List<Long> collectOrderIds(List<Orders> orderList) {
        return orderList.stream()
                .map(Orders::getOrderId)
                .collect(Collectors.toList());
    }

    public List<Integer> collectAddressIds(List<Orders> orderList) {
        return orderList.stream()
                .map(Orders::getAddressId)
                .collect(Collectors.toList());
    }

    public List<Integer> collectTypeIds(List<Orders> orderList) {
        Set<Integer> typeIdsSet = new HashSet<>();
        for (Orders order : orderList) {
            Long orderId = order.getOrderId();
            List<OrderDetail> orderDetails = getOrderDetails(orderId);
            for (OrderDetail orderDetail : orderDetails) {
                typeIdsSet.add(orderDetail.getTypeId());
            }
        }
        return new ArrayList<>(typeIdsSet);
    }

    @NotNull
    public List<OrderDetail> getOrderDetails(Long orderId) {
        Assert.notNull(orderId, "Order ID must not be null");
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderId);
        List<OrderDetail> orderDetails = orderDetailService.list(orderDetailQueryWrapper);
        if (orderDetails == null || orderDetails.isEmpty()) {
            throw new BaseException(ResponseCode.ORDER_STATUS_EXCEPTION);
        }
        return orderDetails;
    }
}
